import Vue from 'vue'
import VueRouter from 'vue-router'
import AdminLayout from '../views/admin/layout.vue';
import LayoutEmpty from '../views/admin/layout_empty.vue';
import HomeLayout from '../views/home/layout.vue';

Vue.use(VueRouter)

const routes = [{
		path: '',
		name: '',
		component: HomeLayout,
		redirect: '/index',
		children: [{
				path: 'index',
				name: 'index',
				component: () => import("../views/home/index.vue"),
				meta: {
					title: "首页"
				}
			},
			{
				path: 'product',
				name: 'product',
				component: () => import("../views/home/product.vue"),
				meta: {
					title: "产品展示"
				}
			},
			{
				path: 'about',
				name: 'about',
				component: () => import("../views/home/about.vue"),
				meta: {
					title: "关于我们"
				}
			}
		]
	},
	{
		path: '/admin/login',
		name: "login",
		component: resolve => require(['@/views/admin/login'], resolve),
		meta: {
			title: "系统登录"
		}
	},
	{
		path: '/admin/auth/role_edit',
		name: 'admin-auth-roleedit',
		component: resolve => require(['@/views/admin/auth/role_edit'], resolve),
		meta: {
			title: "角色管理"
		}
	},
	{
		path: '/admin/auth/menu_edit',
		name: 'admin-auth-menuedit',
		component: resolve => require(['@/views/admin/auth/menu_edit'], resolve),
		meta: {
			title: "编辑菜单"
		}
	}
]

const router = new VueRouter({
	mode: 'history',
	routes
})

export const setRoutes = () => {
	 const menusStr = localStorage.getItem('menus');
	 if(menusStr){
		 const currentRouterNames = router.getRoutes().map(v => v.name)
		if (!currentRouterNames.includes('admin')) {
			//拼装动态路由
			const adminRoute={
				path:'/admin',
				name:"admin",
				component:AdminLayout,
				children:[]
			}

			const menus=JSON.parse(menusStr);
			menus.forEach(item=>{
				if(item.path){
					const itemMenu={
						path:item.path,
						name:item.key,
						meta:{
							title:item.title,
							icon:item.icon
						},
						component:()=>import("@/views"+item.path+".vue")
					}
					adminRoute.children.push(itemMenu);
				}else{
					if(item.children.length>0){
						item.children.forEach(item=>{
							const itemMenu={
								path:item.path,
								name:item.key,
								meta:{
									title:item.title,
									icon:item.icon
								},
								component:()=>import("@/views"+item.path+".vue")
							}
							
							adminRoute.children.push(itemMenu);
							
						})
					}
				}
				router.addRoute(adminRoute);
			})
		}
	 }
}


setRoutes();



export default router;